package com.changwu.cwbase.widget;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.widget.TextView;

import com.changwu.cwbase.R;


@SuppressLint("AppCompatCustomView")
public class CountDownView extends TextView implements Runnable {

    Paint mPaint; //画笔,包含了画几何图形、文本等的样式和颜色信息

    private long[] times;

    private long mday, mhour, mmin, msecond;//天，小时，分钟，秒

    private boolean run = false; //是否启动了

    public CountDownView(Context context, AttributeSet attrs) {
        super(context, attrs);
        mPaint = new Paint();
        TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.TimeTextView);

        array.recycle(); //一定要调用，否则这次的设定会对下次的使用造成影响
    }

    public CountDownView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        mPaint = new Paint();
        TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.TimeTextView);

        array.recycle(); //一定要调用，否则这次的设定会对下次的使用造成影响
    }

    public CountDownView(Context context) {
        super(context);
    }

    public long[] getTimes() {
        return times;
    }

    public void setTimes(long[] times) {
        this.times = times;
        mday = times[0];
        mhour = times[1];
        mmin = times[2];
        msecond = times[3];

    }

    /**
     * 倒计时计算
     */
    private void ComputeTime() {
        msecond--;
        if (msecond < 0) {
            mmin--;
            msecond = 59;
            if (mmin < 0) {
                mmin = 59;
                mhour--;
                if (mhour < 0) {
                    // 倒计时结束
                    mhour = 24;
                    mday--;
                    if (mday < 0) {
                        run = false;
                    }
                }
            }

        }

    }

    public boolean isRun() {
        return run;
    }

    public void setRun(boolean run) {
        this.run = run;
    }

    @Override
    public void run() {
        //标示已经启动
        run = true;

        ComputeTime();
        String strTime = "";
        if (run) {
           /* strTime =mday + "天" + mhour + "时" +
                    mmin + "钟" + msecond + "秒";*/

            strTime = (mhour > 9 ? mhour : "0" + mhour) + ":" + (mmin > 9 ? mmin : "0" + mmin) + ":" + (msecond > 9 ? msecond : "0" + msecond);
        } else {
            /*strTime = 0 + "天" + 0 + "时" +
                    0 + "分" + 0 + "秒";*/
            strTime = "已结束";
        }
        this.setText(strTime);
        if (run) {
            postDelayed(this, 1000);
        }

    }

}
